package fun.codedesign.jdk.thread;

import org.junit.Test;


/**
 * 死锁演示，相互访问对方资源，导致线程死锁
 *
 * @author zengjian
 */
public class DeadLock {
    public static void main(String[] args) {
        final A a = new A();
        final B b = new B();
        new Thread(new Runnable() {
            @Override
            public void run() {
                a.a1(b);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                b.b1(a);
            }
        }).start();
    }

    @Test
    public void testName() {
        final C c = new C();

        new Thread(new Runnable() {

            @Override
            public void run() {
                c.print();

            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                c.print();

            }
        }).start();

    }

    private static class A {
        public synchronized void a1(B b) {
            // 获得a的对象锁
            System.out.println("a1方法" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("试图访问b的b2方法");
            // 试图获得b的对象锁定，执行方法b2
            b.b2();
        }

        public synchronized void a2() {
            System.out.println("a2方法");
        }
    }

    private static class B {
        public synchronized void b1(A a) {
            // 获得b的对象锁定
            System.out.println("b1方法" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("试图访问a的a2方法");
            // 视图获得a的对象锁执行方法
            a.a2();
        }

        public synchronized void b2() {
            System.out.println("b2方法");
        }
    }
}

class C {

    private int i = 0;

    public synchronized void print() {
        try {
            Thread.sleep(1000);
            System.out.println("方法开始");
            Thread.sleep(1000);
            System.out.println("11");
        } catch (InterruptedException e) {
            System.out.println("123");
            e.printStackTrace();
        }
        System.out.println("同步方法" + (i++));
    }
}


